package app.services;

import app.Const;
import app.models.sys.Module;
import app.models.sys.User;
import com.google.common.collect.Lists;
import goja.StringPool;
import goja.security.shiro.AppUser;
import goja.security.shiro.LoginUser;
import goja.security.shiro.UserAuth;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.DisabledAccountException;

import java.util.List;

import static app.Const.FIELD_STATUS;

/**
 * <p>
 * 用户登录权限数据处理
 * </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class SecurityUserData implements goja.security.shiro.SecurityUserData {
    @Override
    public UserAuth auth(AppUser principal) {

        User user = User.dao.findById(principal.getId());
        List<String> modules = Lists.newArrayList();
        List<String> roles = Lists.newArrayList();
        if (user.getNumber("super_admin").intValue() == 1) {
            List<Module> moduleList = Module.dao.findAll();
            for (Module module : moduleList) {

                String permission = module.getStr(Const.FIELD_CODE);
                //管理员也不给领导审批权限
                if (StringUtils.endsWith(permission, "clearing_ok")) {
                    continue;
                }
                modules.add(permission);
            }
        } else {
            final String role = user.getStr("role");
//            roles = Lists.newArrayList(String.valueOf(role));
            List<Module> role_modules = Module.dao.findByRole(role);


            for (Module role_module : role_modules) {
                final String code = role_module.getStr(Const.FIELD_CODE);
                modules.add(code);
            }
        }

        return new UserAuth(roles, modules);
    }

    @Override
    public LoginUser user(String loginName) {
        User user = User.dao.findByLogin(loginName);
        if (user == null) {
            return null;
        } else {

            final int status = user.valInt(FIELD_STATUS);
            if (status == 0) {
                throw new DisabledAccountException("用户已禁用，无法登录!");
            }
            // 0 未知类型
            // 1 管理员
            // 2 客服
            int type = user.valBoolean("super_admin") ? 1 : (user.valBoolean("customer") ? 2 : 0);
            AppUser<User> shiroEmployee = new AppUser<User>(
                    user.valInt(StringPool.PK_COLUMN),
                    user.getStr("username"),
                    user.getStr("emal"),
                    type, status, user);
            return new LoginUser<User>(shiroEmployee, user.getStr("password"), user.getStr("salt"));
        }
    }
}
